package com.glyxybxhtxt.controller.file;

import com.glyxybxhtxt.dataObject.Bxd;
import com.glyxybxhtxt.service.BxdService;
import com.glyxybxhtxt.service.ExportService;
import com.glyxybxhtxt.util.DownloadFile;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @Author lrt
 * @Date 2021/1/7 17:34
 * @Version 1.0
 * Describe 导出功能
 **/
@RestController
public class export {

    @Resource
    private ExportService exportService;

    @Resource
    private BxdService bxdService;

    @RequestMapping(value = "/export/{id}",method = RequestMethod.GET)
    public String export2xlsx(@PathVariable String id, HttpServletRequest request, HttpServletResponse response){
        boolean isExported = isExport(id);
        if(isExported){
            return "<h1 style='color: red; text-align: center'>不好意思，您或其他人已经导出过一次，无法再重新导出。</h1>";
        }
        String fileName = "export.xls";// 设置文件名，根据业务需要替换成要下载的文件名
        exportService.exportXlsx(id);
        if (fileName != null) {
            //设置文件路径
            // 开发环境需要
            // String realPath = "src/main/resources/static/";
            // 生成需要
            String realPath = "C:\\Program Files\\Apache Software Foundation\\Tomcat 9.0\\webapps\\bx\\WEB-INF\\classes\\static";
            File file = new File(realPath , fileName);
            if (file.exists()) {
                DownloadFile.DownloadExcelByFile(response, file, fileName);
            }
        }

        // 导出成功后，记录到数据库，防止重复导出，默认只能导出一次
        Bxd bxd = new Bxd();
        bxd.setId(Integer.parseInt(id));
        bxd.setIsExported(1);
        int updateSure = bxdService.upBxdByExport(bxd);
        if(updateSure != 0){
            return "<h1 style='color: red; text-align: center'>导出成功</h1>";
        }
        return null;
    }

    /**
     * 创建是否导出过，因为只允许导出一次
     * 导出过为 true，否则为 false
     */
    public boolean isExport(String id) {
        Bxd oneBxd = bxdService.selonebxd(Integer.parseInt(id));
        System.out.println(oneBxd);
        if(oneBxd.getIsExported() == 1){
            return true;
        }
        return false;
    }
}
